﻿@page "/"

@using System.Security.Claims
@using System.Text.Json
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using System.Net.Http.Headers
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject IAccessTokenProvider AccessTokenProvider

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

<div class="alert alert-warning" role="alert">
    Before authentication will function correctly, you must configure your provider details in <code>Program.cs</code>
</div>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?"/>

@if (_claims.Count() > 0)
{
    <p>
        @_accessToken
    </p>

    <ul>
        @foreach (var claim in _claims)
        {
            <li>@claim.Type: @claim.Value</li>
        }
    </ul>

    <code style="display: block; white-space: pre-wrap; text-align: left">
        @{
            var apiResponse = "No API response";
            if (_claimsResponseString != null)
            {
                apiResponse = JsonSerializer.Serialize(JsonDocument.Parse(_claimsResponseString), new JsonSerializerOptions
                {
                    WriteIndented = true
                });
            }
        }
        @apiResponse;
    </code>
}

@code {

        protected override async Task OnInitializedAsync()
        {
            await GetClaimsPrincipalData();
            await base.OnInitializedAsync();
        }

        private IEnumerable<Claim> _claims = Enumerable.Empty<Claim>();
        private string? _accessToken;
        private string? _claimsResponseString;

        private async Task GetClaimsPrincipalData()
        {
            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;

            if (user.Identity.IsAuthenticated)
            {
                _claims = user.Claims;

                var result = await AccessTokenProvider.RequestAccessToken();
                result.TryGetToken(out var token);
                _accessToken = token?.Value;

                var client = new HttpClient();
                var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:44303/api/claims");
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
                _claimsResponseString = await (await client.SendAsync(request)).Content.ReadAsStringAsync();
            }
        }
}
